package cn.itmtr.document.download.common.exception;

import cn.hutool.core.util.StrUtil;
import cn.itmtr.document.download.common.util.Result;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 *
 * @author mtr
 * @since 2021-08-08
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        recordingRequestInfo(request);
        log.error(e.getMessage(), e);
        return Result.error("不支持 " + e.getMethod() + " 请求");
    }

    /**
     * 自定义异常
     */
    @ExceptionHandler(ItmtrException.class)
    public Result handleException(HttpServletRequest request, ItmtrException e) {
        recordingRequestInfo(request);
        log.error(e.getMessage(), e);
        return Result.error(e);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result notFount(HttpServletRequest request, RuntimeException e) {
        String requestInfo = recordingRequestInfo(request);
        log.error("运行时异常:", e);
        return Result.error("服务器异常，请稍后再试或联系客服");
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(HttpServletRequest request, Exception e) {
        String requestInfo = recordingRequestInfo(request);
        log.error(e.getMessage(), e);
        return Result.error("服务器错误，请稍后再试或联系客服");
    }

    /**
     * 记录请求信息 并返回
     *
     * @param request request
     * @return java.lang.String
     * @author mtr
     * @date 2021/8/8
     */
    public String recordingRequestInfo(HttpServletRequest request) {
        // 请求地址
        String requestUri = request.getRequestURI();
        // 请求参数
        String params = JSON.toJSONString(request.getParameterMap());

        log.error("请求地址：{}", requestUri);
        log.error("请求参数：{}", params);
        return StrUtil.format("- 请求地址：{}\n- 请求参数：{}\n", requestUri, params);
    }

}
